package de.hauck.rtmidlet;

import java.io.DataInputStream;
import java.io.IOException;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.Display;

import de.hauck.rtmidlet.model.Configuration;
import de.hauck.rtmidlet.model.StockBean;
import de.hauck.rtmidlet.model.StockStore;
import de.hauck.rtmidlet.views.FormSettingsMenu;

public class FileSystemImportThread implements Runnable {

	Configuration c;
	StockStore _myStore;
	Display _disp;
	FormSettingsMenu _formSettings;
	RTMidlet _main;


	public FileSystemImportThread(RTMidlet rtmidlet, StockStore myStore, Display disp, FormSettingsMenu fs) {
		_myStore = myStore;
		_main=rtmidlet;
		_formSettings = fs;
		_disp = disp;

		new Thread(this).start();
	}

	public void run() {

		importCSV();
	}

	private void importCSV() {
		try {
			System.out.println("try to import: "+c.importURL);
			FileConnection fc = (FileConnection) Connector.open("file:///"+c.importURL, //c.exportURL,
					Connector.READ);
			if (!fc.exists()) {
				throw new IOException("File does not exist");
			}
			DataInputStream is = fc.openDataInputStream();
			
			try {
				StringBuffer b = new StringBuffer();
				int ch;
				while ((ch = is.read()) != -1) {
					b.append((char) ch);
				}
				parseInputString(b.toString());
				
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (is != null) {
					is.close();
				}
				if (fc != null) {
					fc.close();
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	private void parseInputString(String str) {
		System.out.println("Parsing: "+str);
		int offset=0;
		int counter=0;
		Vector stockVec = new Vector();
		StockBean stock=new StockBean();
		try {
			for (int i=0; i<str.length(); i++) {
				if (str.charAt(i)=='#') {
					while (str.charAt(i)!='\n') {
						//do nothing
						i++;
					}
					offset=i+1;
				}
				else if (str.charAt(i)==',') {
					String token=str.substring(offset,i);
					stock.setToken(counter, token);
					counter++;
					offset=i+1;
				} else if (str.charAt(i)=='\n') {			
					String token=str.substring(offset,i);
					stock.setToken(counter, token);
					stockVec.addElement(stock);
					counter=0;
					offset=i+1;
					stock.printBean();
					stock=new StockBean();			
				}
			}
			_myStore.setStocksVector(stockVec);
			_formSettings.showImportSuccess();
		} catch (Exception e) {
			_main.alert("Error", e.getMessage(),c.ALERT_WAIT_TIME);
			e.printStackTrace();
		}
	}
}
